package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.foundations.dto.response.ServeAggregationResDTO;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.mapper.*;
import com.jzo2o.foundations.model.domain.*;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.*;
import com.jzo2o.foundations.service.IRegionService;
import com.jzo2o.foundations.service.IServeItemService;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 区域管理
 *
 * @author itcast
 * @create 2023/7/17 16:50
 **/
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    @Autowired
    private IServeItemService iServeItemService;

    @Autowired
    private ServeMapper serveMapper;

    @Autowired
    private IRegionService iRegionService;

    @Autowired
    private RegionMapper regionMapper;

    @Autowired
    private ServeItemMapper serveItemMapper;

    @Autowired
    private ServeTypeMapper serveTypeMapper;

    @Autowired
    private ServeSyncMapper serveSyncMapper;

    @Autowired
    private RestHighLevelClient client;
    /**
     * 分页查询区域的服务信息
     *
     * @param servePageQueryReqDTO
     * @return
     */

    @Override
    public PageResult<ServeResDTO> findByPage(ServePageQueryReqDTO servePageQueryReqDTO) {
        return PageHelperUtils.selectPage(servePageQueryReqDTO,
                () -> baseMapper.queryListByRegionId(servePageQueryReqDTO.getRegionId()));
    }

    /**
     * 区域内的服务批量添加
     *
     * @param serveUpsertReqDTOList
     *
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(List<ServeUpsertReqDTO> serveUpsertReqDTOList) {
        //参数是服务ID，区域ID，价格
        List<Serve> list = new ArrayList<>();
        serveUpsertReqDTOList.forEach(serveDTO->{
            //1. 服务项目必须是启用状态的才能添加到区域
            ServeItem serveItem = iServeItemService.getById(serveDTO.getServeItemId());
            if (serveItem == null || serveItem.getActiveStatus() != 2) {
                throw new ForbiddenOperationException("当前服务状态异常");
            }
            //2. 一个服务项目对于一个区域，只能添加一次
            Integer integer = serveMapper.selectCount(new LambdaQueryWrapper<Serve>()
                    .eq(Serve::getRegionId, serveDTO.getRegionId())
                    .eq(Serve::getServeItemId, serveDTO.getServeItemId()));
            if(integer == null || integer > 0){
                throw new ForbiddenOperationException("当前服务在当前区域已经添加");
            }

            //把当前的服务添加到集合
            Serve serve = new Serve();
            Region region = iRegionService.getById(serveDTO.getRegionId());
            if(region == null || region.getCityCode() == null) {
                throw new ForbiddenOperationException("当前区域异常");
            }

            BeanUtil.copyProperties(serveDTO, serve);
            BeanUtil.copyProperties(region, serve);
            list.add(serve);
        });
        //批量插入
        this.saveBatch(list);
    }

    /**
     * 删除区域中服务状态为草稿的服务
     *
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        Serve serve = serveMapper.selectById(id);
        if(serve == null || serve.getSaleStatus() != 0) {
            throw new ForbiddenOperationException("服务状态异常，请重试");
        }
        this.removeById(id);
    }

    /**
     * 修改区域中的服务状态为上架
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeSaleStatusToUp(Long id) {
        //在区域服务列表中点击上架，此服务在该区域将生效（本质就是要修改区域服务的状态为2）
        //上架成功的必要条件有两个：1) 区域服务当前非上架状态   2) 服务项目是启用状态
        Serve serve = serveMapper.selectById(id);
        if (serve == null) {
            throw new ForbiddenOperationException("服务不存在");
        }
        if(serve.getSaleStatus() == 2) {
            throw new ForbiddenOperationException("服务已经是上架状态啦");
        }
        ServeItem serveItem = iServeItemService.getById(serve.getServeItemId());
        if(serveItem == null) {
            throw new ForbiddenOperationException("服务项目不存在");
        }
        if(serveItem.getActiveStatus() != 2) {
            throw new ForbiddenOperationException("服务项目不是启用状态");
        }
        this.update(new LambdaUpdateWrapper<Serve>()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, 2));
        //4）添加同步表数据
        addServeSync(id);
    }

    /**
     * 新增服务同步数据
     *
     * @param serveId 服务id
     */
    private void addServeSync(Long serveId) {
        //服务信息
        Serve serve = baseMapper.selectById(serveId);
        //区域信息
        Region region = regionMapper.selectById(serve.getRegionId());
        //服务项信息
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        //服务类型
        ServeType serveType = serveTypeMapper.selectById(serveItem.getServeTypeId());

        ServeSync serveSync = new ServeSync();
        serveSync.setServeTypeId(serveType.getId());
        serveSync.setServeTypeName(serveType.getName());
        serveSync.setServeTypeIcon(serveType.getServeTypeIcon());
        serveSync.setServeTypeImg(serveType.getImg());
        serveSync.setServeTypeSortNum(serveType.getSortNum());

        serveSync.setServeItemId(serveItem.getId());
        serveSync.setServeItemIcon(serveItem.getServeItemIcon());
        serveSync.setServeItemName(serveItem.getName());
        serveSync.setServeItemImg(serveItem.getImg());
        serveSync.setServeItemSortNum(serveItem.getSortNum());
        serveSync.setUnit(serveItem.getUnit());
        serveSync.setDetailImg(serveItem.getDetailImg());
        serveSync.setPrice(serve.getPrice());

        serveSync.setCityCode(region.getCityCode());
        serveSync.setId(serve.getId());
        serveSync.setIsHot(serve.getIsHot());
        serveSyncMapper.insert(serveSync);
    }

    /**
     * 修改区域的服务状态为下架
     *
     * @param id
     */
    @Override
    public void changeSaleStatusToDown(Long id) {
        //在区域服务列表中点击上架，此服务在该区域将生效（本质就是要修改区域服务的状态为2）
        //上架成功的必要条件有两个：1) 区域服务当前非上架状态   2) 服务项目是启用状态
        Serve serve = serveMapper.selectById(id);
//        if (serve == null) {
//            throw new ForbiddenOperationException("服务不存在");
//        }
        if(serve.getSaleStatus() != 2) {
            throw new ForbiddenOperationException("服务不是上架状态哦");
        }
//        ServeItem serveItem = iServeItemService.getById(serve.getServeItemId());
//        if(serveItem == null) {
//            throw new ForbiddenOperationException("服务项目不存在");
//        }
//        if(serveItem.getActiveStatus() != 2) {
//            throw new ForbiddenOperationException("服务项目不是启用状态");
//        }
        this.update(new LambdaUpdateWrapper<Serve>()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, 1));

        serveSyncMapper.deleteById(id);
    }

    /**
     * 修改区域中的服务状态为热门
     *
     * @param id
     */
    @Override
    public void changeHotToOn(Long id) {
        //判断是不是热门
        Serve serve = this.getById(id);
        if(serve == null || serve.getIsHot() == 1) {
            throw new ForbiddenOperationException("服务不存在或者是服务已经是热门啦");
        }

        this.update(new LambdaUpdateWrapper<Serve>()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot, 1)
                .set(Serve::getHotTimeStamp, new Date().getTime()));
    }

    /**
     * 修改区域中的服务状态为不是热门
     *
     * @param id
     */
    @Override
    public void changeHotToOff(Long id) {
        //判断是不是热门
        Serve serve = this.getById(id);
        if(serve == null || serve.getIsHot() == 0) {
            throw new ForbiddenOperationException("服务不存在或者是服务已经不是热门啦");
        }

        this.update(new LambdaUpdateWrapper<Serve>()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot, 0));
    }

    /**
     * 实现了获取首页服务列表
     *
     * @param regionId
     * @return
     */
    @Caching(
            cacheable = {
                    //返回数据为空，则缓存空值30分钟，这样可以避免缓存穿透
                    @Cacheable(value = RedisConstants.CacheName.SERVE_ICON, key ="#regionId" ,
                            unless ="#result.size() > 0",cacheManager = RedisConstants.CacheManager.THIRTY_MINUTES),

                    //返回值不为空，则永久缓存数据
                    @Cacheable(value = RedisConstants.CacheName.SERVE_ICON, key ="#regionId" ,
                            unless ="#result.size() == 0",cacheManager = RedisConstants.CacheManager.FOREVER)
            }
    )
    @Override
    public List<ServeCategoryResDTO> getFirstPageServeList(Long regionId) {
        List<ServeCategoryResDTO> list = baseMapper.getFirstPageServeList(regionId);
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }
        //这边要注意， 默认展示2个服务分类，升序取前2个
        List<ServeCategoryResDTO> newlist =CollectionUtil.sub(list, 0, Math.min(list.size(), 2));

        //每个服务分类下展示4个服务项目
        newlist.forEach(serveCategoryResDTO -> {
            serveCategoryResDTO.setServeResDTOList(
                    CollectionUtil.sub(serveCategoryResDTO.getServeResDTOList(), 0, Math.min(serveCategoryResDTO.getServeResDTOList().size(), 4)));
        });

        return newlist;
    }

    /**
     * 实现了获取首页精选推荐
     *
     * @param regionId
     * @return
     */
    @Caching(cacheable = {
            //返回数据不为空,存储永久
            @Cacheable(value = RedisConstants.CacheName.HOT_SERVE,
                    key = "#regionId",
                    cacheManager = RedisConstants.CacheManager.FOREVER,
                    unless = "#result.size() > 0"
            ),
            //返回数据为空, 存储30分钟
            @Cacheable(value = RedisConstants.CacheName.HOT_SERVE,
                    key = "#regionId",
                    cacheManager = RedisConstants.CacheManager.THIRTY_MINUTES,
                    unless = "#result.size() <= 0"
            )
    })
    @Override
    public List<ServeAggregationSimpleResDTO> getHotServeList(Long regionId) {
        //设置是热门，上架的，修改时间降序的
        Region region = iRegionService.getById(regionId);
        if(ObjectUtil.isEmpty(region)) {
            return Collections.emptyList();
        }
        return baseMapper.getHotServeList(regionId);
    }

    /**
     * 实现了获取选择的服务详情的接口
     *
     * @param id
     * @return
     */
    @Override
    public ServeAggregationSimpleResDTO getHotServeInfo(Long id) {
        //这里采用的是分步查询
        //先查服务表
        Serve serve = baseMapper.selectById(id);
        if(ObjectUtil.isEmpty(serve)) {
            throw new ForbiddenOperationException("当前服务不存在哦");
        }

        ServeItem serveItem = iServeItemService.getById(serve.getServeItemId());
        if(ObjectUtil.isEmpty(serveItem)) {
            throw new ForbiddenOperationException("当前服务项目不存在哦");
        }

        ServeAggregationSimpleResDTO serveAggregationSimpleResDTO = BeanUtil.copyProperties(serve, ServeAggregationSimpleResDTO.class);
        serveAggregationSimpleResDTO.setServeItemId(serveItem.getId());
        serveAggregationSimpleResDTO.setServeItemName(serveItem.getName());
        serveAggregationSimpleResDTO.setServeItemImg(serveItem.getImg());
        serveAggregationSimpleResDTO.setUnit(serveItem.getUnit());
        serveAggregationSimpleResDTO.setDetailImg(serveItem.getDetailImg());


        return serveAggregationSimpleResDTO;
    }

    /**
     * 获取区域ID的全部服务分类
     *
     * @param regionId
     * @return
     */
    @Override
    public List<ServeAggregationTypeSimpleResDTO> getServeTypeList(Long regionId) {

        return baseMapper.getServeTypeList(regionId);
    }

    /**
     * 服务搜索
     *
     * @param cityCode    城市编码
     * @param keyword     关键词
     * @param serveTypeId 服务类型id
     * @return 服务项目信息
     */
    @Override
    public List<ServeSimpleResDTO> search(String cityCode, String keyword, Long serveTypeId) {
        //1. 创建请求对象
        SearchRequest request = new SearchRequest("serve_aggregation");

        //2. 封装请求参数
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //城市编码
        boolQuery.must(QueryBuilders.termQuery("city_code", cityCode));
        //服务类型id
        if (serveTypeId != null) {
            boolQuery.must(QueryBuilders.termQuery("serve_type_id", serveTypeId));
        }
        //关键词
        if (StrUtil.isNotEmpty(keyword)) {
            boolQuery.must(QueryBuilders.multiMatchQuery(keyword, "serve_item_name", "serve_type_name"));
        }
        request.source().query(boolQuery);//查询
        request.source().sort("serve_item_sort_num", SortOrder.ASC);//排序

        //3. 执行请求
        SearchResponse response = null;

        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //4. 处理返回结果   List<ServeSimpleResDTO>
        if (response.getHits().getTotalHits().value == 0) {
            return List.of();
        }
        return Arrays.stream(response.getHits().getHits())
                .map(e -> JSONUtil.toBean(e.getSourceAsString(), ServeSimpleResDTO.class))
                .collect(Collectors.toList());
    }

    /**
     * 根据ID查询服务详情
     *
     * @param id 服务id
     * @return 服务详情
     */
    @Override
    public ServeAggregationResDTO findServeDetailById(Long id) {
        return baseMapper.findServeDetailById(id);
    }
}
